<template>
  <div id="app" >
    <div class="chat-container">
      <div class="messages" >
        <div v-for="message in messages" :key="message.id" :class="{'sent': message.sent, 'received': !message.sent}">
          <VueMarkdown
            class="api-content"
            :source="message.text"
            id="content"
        />
        </div>
      </div>
      <!-- <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="和我聊聊天吧..."> -->
      <div style="display: flex; width: 100%; margin-top: 10px;">
        <textarea 
          v-model="newMessage" 
          @keyup.enter="sendMessage" 
          placeholder="和我聊聊天吧..."
          rows="2"
          style="width: 100%; padding: 10px; margin-top: 10px; border-radius: 10px; border: 1px solid #ccc; resize: none;"/>
        <button 
            @click="sendMessage" 
            style="margin-left: -1px; padding: 0 15px; border-radius: 0 10px 10px 0; border: 1px solid #ccc; border-left: none; background-color: #f0f0f0; cursor: pointer;">
            发送
          </button>
      </div>
    </div>
  </div>
</template>
 

<script>
import VueMarkdown from 'vue-markdown';
export default {
  name: 'App',
  components: { VueMarkdown },
  data() {
    return {
      url: "ws://127.0.0.1:8080/websocket/message",
      //message: "",
      text_content: "",
      ws: null,
      messages: [],
      newMessage: '',
      messageId: 0,
      reveMessageId: 0,
      messageBody :{
          sessionId: '',
          userName: '',
          message: ''
      }
    };
  },  

  created() {
      const wsuri = this.url;
      this.ws = new WebSocket(wsuri);
      this.ws.onopen = (event) => {
        this.messages.push({ id: Date.now(), text: "系统消息：已经打开连接!" + "\n", sent: true });
      };
      this.ws.onmessage = (event) => {
        console.log("原始 event.data:", event.data); // 检查类型
        const obj = JSON.parse(event.data); // 直接解析
        console.log("解析后的 obj:", obj); // 确认是否正确
        console.log("obj.message:", obj.message); // 应该能正确输出

        this.messageBody = event.data;

          if (0 === this.messageId) { 
            this.messages.push({
              id: Date.now(),
              text: obj.message + "\n",
              sent: true
            });
          }else{
            const lastMessage = this.messages[this.messages.length - 1];
            if (lastMessage.id === this.messageId) { 
              console.log('消息不存在');             
              this.reveMessageId = Date.now();
              const newMsg2 = { id: this.reveMessageId, text: obj.message, sent: true };              
              this.messages.push(newMsg2);
            }else if (lastMessage.id === this.reveMessageId) { 
              console.log('消息存在');  
              this.$set(this.messages[this.messages.length - 1], 'text', lastMessage.text + obj.message);
            }else{
              console.log('error');
            }
        }
      };
      this.ws.onclose = (event) => {
        console.log(event);
        this.messages.push({ id: Date.now(), text: "已经关闭连接!" + "\n", sent: true });
      };
      this.ws.onerror = (event) => {
        console.log(event);        
      };
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim()) {
        console.log(this.newMessage); 
        const messageBodyObj = JSON.parse(this.messageBody); 
        messageBodyObj.message = this.newMessage;
        const messageBodyStr = JSON.stringify(messageBodyObj);

        if (this.ws) {
          console.log('send this.newMessage');
          console.log(messageBodyStr);
          this.ws.send(messageBodyStr);
        }else{
          console.log('ws is null');
        }

        // 1. 只生成一次 ID
        const currentMessageId = Date.now();

        // 2. 用这个 ID 创建新消息 
        const newMsg = { id: currentMessageId, text: this.newMessage, sent: true };
        this.messages.push(newMsg);
        this.newMessage = ''; // 清空输入框

        // 3. 用同一个 ID 来设置 messageId 标记
        this.messageId = currentMessageId;
        
        console.log('发送消息，设置 messageId 为:', this.messageId);
      }
    }
  }
}
</script>
 
<style>
.chat-container {
  max-width: 80%;
  margin: auto;
  border: 1px solid #ccc;
  padding: 10px;
}
.messages {
  height: 600px;
  overflow-y: auto;
  border: 1px solid #ddd;
  padding: 10px;
}
.messages div {
  padding: 5px;
  margin-bottom: 5px;
  border-radius: 5px;
  white-space: pre-wrap; /* 确保换行符生效 */
  word-wrap: break-word; /* 确保长单词换行 */
}
.sent {
  background-color: #f0f0f0;
  padding: 10px 15px;
  border-radius: 10px;
  max-width: 100%;
  /* text-align: left; */
}
.received {
  background-color: #e6f7ff;
  padding: 10px 15px;
  border-radius: 10px;
  max-width: 100%;
  /* text-align: right; */
}
input {
  width: 100%;
  padding: 10px;
  margin-top: 10px;
  border-radius: 10px; /* 添加圆角属性 */
  border: 1px solid #ccc; /* 添加边框 */
}
</style>